<?php

/**
 * Created by PhpStorm.
 * @package    art
 * @copyright  Copyright (c) 2013 LaZaDa SEA
 * @author     long.nguyen-thanh <long.nguyen-thanh@lazada.com
 * @date       5/22/14 12:55 PM
 * @ID         $Id: CliController.php 35 2014-05-28 02:13:45Z anhkhoa.nguyen2610@gmail.com $,${Id}
 */
class CliController extends Zend_Controller_Action {
    public function indexAction() {
        echo __FILE__;
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout->disableLayout();
        die();
    }

    /**
     * php cli/index.php --env=developer --module=default --controller=cli --action=scanqueue
     */
    public function scanqueueAction() {
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout->disableLayout();

        $tblQueue = new Zendvn_Model_Table_QueueItem();
        $tblLink  = new Zendvn_Model_Table_LinkContent();

        $items = $tblQueue->listItem();

        if (!empty($items)) {
            foreach ($items as $val) {
                $data               = $this->_getContentUrl($val['website']);
                $data['id_item']    = $val['id'];
                $tblLink->saveItem($data);
                $tblQueue->deleteItem($val['id']);
            }
        }

    }

    /**
     * php cli/index.php --env=developer --module=default --controller=cli --action=updatecontent
     */
    public function updatecontentAction(){
        $this->_helper->viewRenderer->setNoRender();
        $this->_helper->layout->disableLayout();

        $tblLink  = new Zendvn_Model_Table_LinkContent();

        $items = $tblLink->listItem();

        if (!empty($items)) {
            foreach ($items as $val) {
                $data               = $this->_getContentUrl($val['domain']);
                $tblLink->updateItemByID($data,$val['id']);
            }
        }
    }

    /**
     * @param $url
     * @return array
     */
    private function _getContentUrl($url) {

        $crawler = new Zendvn_CrawlContent();
        $url = urldecode($url);
        preg_match('/^((http|https):\/\/)?([^\/]+)/i', $url, $domain);

        if (empty($domain[1])) {
            $domain = 'http://' . $domain[2] . '/';
        } else {
            $domain = $domain[0] . '/';
        }
        return $crawler->getPageInfo($url, $domain);
    }
}